package com.qf.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * 初始化构建连接ES服务器
 */
@Configuration
public class ElasticsearchConfig {

    @Value("${elasticsearch.host}")
    private List<String> hosts;

    @Value("${elasticsearch.port}")
    private List<Integer> ports;

    @Bean
    public RestHighLevelClient restHighLevelClient(){

        //1. 判断
        if (hosts.size() != ports.size()) {
            throw  new RuntimeException("[连接ES] host和port数量不一致!!!");
        }

        //2. 构建HttpHost
        HttpHost[] httpHostArray = new HttpHost[hosts.size()];
        for (int i = 0; i < hosts.size(); i++) {
            HttpHost httpHost = new HttpHost(hosts.get(i), ports.get(i));
            httpHostArray[i] = httpHost;
        }

        //3. 构建RestClient
        RestClientBuilder restClientBuilder = RestClient.builder(httpHostArray);

        //4. 构建RestHighLevelClient
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(restClientBuilder);

        //5. 返回
        return restHighLevelClient;
    }
}
